// components/blog-ctrl/blog-ctrl.js
let userInfo = {}
const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    loginShow: false,
    modalShow: false,
    content: ""
  },
  externalClasses: [
    'iconfont',
    'icon-pinglun',
    'icon-fenxiang'
  ],

  /**
   * 组件的方法列表
   */
  methods: {
    onComment() {
      wx.requestSubscribeMessage({
        tmplIds: ['bSop-TFBoZPUpy7O0hyckpX143T1F936-LSBTsqSAzY'],
        success (res) { 
          console.log(">>订阅",res)
        },
        fail(err){
          console.log(">>>订阅错误",err)
        }
      })
      wx.getSetting({
        success: (res) => {
          console.log(res.authSetting)
          if (res.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success: (res) => {
                userInfo = res.userInfo
              }
            })
            this.setData({
              modalShow: true
            })
          } else {
            this.setData({
              loginShow: true
            })
          }
        }
      })
    },
    onLoginsuccess(event) {
      userInfo = event.detail
      this.setData({
        loginShow: false
      }, () => {
        this.setData({
          modalShow: true
        })
      })
    },
    onLoginfail() {
      wx.showModal({
        title: "授权用户才可评价"
      })
    },


    onSend(event) {
      //插入数据库
      let content = event.detail.value.content
      let fromId = event.detail.fromId
      if (content.trim() == "") {
        wx.showModal({
          title: "评论不能为空",
          content: ""
        })
        return
      }
      wx.showLoading({
        title: '评价中',
        mask: true
      })
      console.log(userInfo)
      db.collection("blog-comment").add({
        data: {
          content,
          createTime: db.serverDate(),
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then((res) => {
      // 推送模板信息

        wx.cloud.callFunction({
          name: "sendMessage",
          data: {
            content,
            fromId,
            blogId: this.properties.blogId,
            nickName: userInfo.nickName,
          }
        }).then((res)=>{
          console.log(res)
        })
        wx.hideLoading()
        wx.showToast({
          title: '评论成功',
        })
        this.setData({
          modalShow: false,
          content: ""
        })
        this.triggerEvent("refreshComment")
      })
    },
  }
})